import enums.ResponseType;
import request.user.UserLoginRequest;
import request.user.UserRegisterRequest;
import response.ErrorResponse;
import response.Response;
import response.user.UserLoginResponse;
import response.user.UserRegisterResponse;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class LoginHandler extends KeyAdapter implements ActionListener {

    private LoginView loginView;

    public LoginHandler(LoginView loginView) {
        this.loginView = loginView;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jButton = (JButton) e.getSource();
        String text = jButton.getText();
        if ("点此进行注册".equals(text)) {
            register();
        } else if ("登录".equals(text)) {
            login();
        }
    }

    private void register() {
        UserRegisterRequest userRegisterRequest = new UserRegisterRequest(loginView.getUserNameField().getText(), new String(loginView.getPasswordField().getPassword()), null, null);
        Response response = ConnectionUtil.makeConnection(userRegisterRequest);
        if (response.getType().equals(ResponseType.UserRegister)) {
            UserRegisterResponse userRegisterResponse = (UserRegisterResponse) response;
                JOptionPane.showMessageDialog(loginView, "注册成功！");
            }
        else if(response.getType().equals(ResponseType.Error)) {
            ErrorResponse errorResponse=(ErrorResponse) response;
            JOptionPane.showMessageDialog(loginView, errorResponse.getResponseErrorCode().getMessage());
        }

    }

    private void login() {
        UserLoginRequest userLoginRequest = new UserLoginRequest(loginView.getUserNameField().getText(), new String(loginView.getPasswordField().getPassword()));
        Response response = ConnectionUtil.makeConnection(userLoginRequest);
        if (response.getType().equals(ResponseType.UserLogin)) {
            UserLoginResponse userLoginResponse = (UserLoginResponse) response;
                loginView.dispose();
                new ContactsView(userLoginRequest.getUsername());
        }
        else if(response.getType().equals(ResponseType.Error)) {
            ErrorResponse errorResponse=(ErrorResponse) response;
            JOptionPane.showMessageDialog(loginView, errorResponse.getResponseErrorCode().getMessage());
        }
    }

    @Override
    public void keyPressed(KeyEvent e) {
        if (KeyEvent.VK_ENTER == e.getKeyCode()) {
            login();
        }
    }

}
